class DesiresController < ApplicationController
  include ControllerHelper
  before_filter :require_admin
  def new
    set_form_settings
    @page["name"] = "desire"
    @desire = Desire.new
    render :layout => "form"
  end

  def create
    begin
      @desire = Desire.new(params[:desire])
      if @desire.save
        redirect_to desire_admin_path(:status => "all") and return
      else
        set_form_settings
        @page["name"] = "desire"
        render :action => "new", :layout => "form"
      end
    rescue
      flash[:notice] = I18n.t "site.message.corrupted_html"
      set_form_settings
      @page["name"] = "desire"
      render :action => "new", :layout => "form"
    end
  end

  def admin
    per_page = params[:per_page] ||= @site["per_page"]["admin"]["desires"]
    conditions = []
    conditions = merge_conditions(conditions, ["status = ?", "approved"]) if params[:status] == "approved"
    conditions = merge_conditions(conditions, ["status <> ?", "approved"]) if params[:status] == "banned"
    @desires = Desire.find(:all, :conditions => conditions).uniq.paginate(:page => params[:page], :per_page => per_page)
    set_admin_settings
    render :layout => "cms"
  end

  def destroy
    @desire = Desire.find(:first, :conditions => ["id = ?", params[:id]])
    if @desire
      @desire.destroy
    else
      flash[:notice] = I18n.t "site.message.no_desire"
    end
    redirect_to desire_admin_path(:status => "all")
  end

  def edit
    set_form_settings
    @page["name"] = "desire"
    @desire = Desire.find(:first, :conditions => ["id = ?", params[:id]])
    if @desire.nil?
      flash[:notice] = I18n.t "site.message.no_desire"
      redirect_to desire_admin_path(:status => "all") and return
    else
      render :layout => "form"
    end
  end

  def update
    @desire = Desire.find(:first, :conditions => ["id = ?", params[:id]])
    if @desire.nil?
      flash[:notice] = I18n.t "site.message.no_desire"
      redirect_to desire_admin_path(:status => "all") and return
    else
      if @desire.update_attributes(params[:desire])
        redirect_to desire_admin_path(:status => "all") and return
      else
        set_form_settings
        @page["name"] = "desire"
        render :layout => "form", :action => "edit", :id => params[:id]
      end
    end
  end

  def approve_ban
    desire = Desire.find(params[:id])
    old_status = desire.status == "approved" ? "approved" : "banned"
    desire.status = desire.status == "approved" ? "banned" : "approved"
    desire.save
    redirect_to desire_admin_path(:status => old_status)
  end

end
